//
//  MZAlertViewController.swift
//  MZTool
//
//  Created by gby on 2023/1/29.
//

import UIKit

typealias MZAlertActionHander = (_ action: MZAlertAction) -> Void

public class MZAlertAction: UIView {
    
    public static let ACTIONNotifName = Notification.Name("NotificationName_MGSALERT_ACTION_")
    
    public var titleColor: UIColor?{
        didSet{
            if self.titleColor != nil{
                self.titleLab.textColor = self.titleColor
            }
        }
    }
    public var titleFont: UIFont?{
        didSet{
            if self.titleFont != nil {
                self.titleLab.font = self.titleFont
            }
        }
    }
    public var actionEnabled: Bool = true
    
    private(set) lazy var titleLab: UILabel = UILabel.init(16, color: UIColor.white, aligment: .center)
    private lazy var highlisthedView: UIView = UIView.init()
    private var highlighted: Bool = false{
        didSet{
            self.highlisthedView.isHidden = !self.highlighted
        }
    }
    private var actionhander: MZAlertActionHander?
    
    public required convenience init(title: String = "", _ hander: @escaping (_ action: MZAlertAction) -> Void){
        self.init()
        layoutUI()
        actionhander = hander
        titleLab.text = title
        let tap: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(actionTouchUpInside))
        isUserInteractionEnabled = true
        addGestureRecognizer(tap)
    }
    
    private func layoutUI() {
        backgroundColor = UIColor.clear
        highlisthedView.backgroundColor = UIColor.black.withAlphaComponent(0.05)
        titleLab.sizeToFit()
        addSubview(highlisthedView)
        addSubview(titleLab)
        highlisthedView.translatesAutoresizingMaskIntoConstraints = false
        highlisthedView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        highlisthedView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        highlisthedView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        highlisthedView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        titleLab.translatesAutoresizingMaskIntoConstraints = false
        titleLab.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        titleLab.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        titleLab.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        titleLab.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        highlighted = false
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        highlisthedView.isHidden = true
    }
    
    @objc private func actionTouchUpInside(){
        guard actionEnabled else{return}
        actionhander?(self)
        NotificationCenter.default.post(name: MZAlertAction.ACTIONNotifName, object: nil)
    }
    
    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard actionEnabled else{return}
        highlighted = true
    }
    
    public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        
    }
    
    public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard actionEnabled else{return}
        highlighted = false
    }
    
    public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard actionEnabled else{return}
        highlighted = false
    }
}


public class MZAlertViewController: UIViewController {
    
    private var actionList: [MZAlertAction] = []
    private lazy var titleLab: UILabel = UILabel.init(18, weight: .bold, color: .black, aligment: .center)
    private lazy var messageLab: UILabel = UILabel.init(14, color: .black, aligment:.center)
    private lazy var titleAttriStr: NSMutableAttributedString = NSMutableAttributedString.mz.initWith(text: "", font: UIFont.mz.size(18), color: .black, alignment: .center)
    private var messageAttriStr: NSMutableAttributedString?
    public var titleColor: UIColor{
        set{
            self.titleLab.textColor = newValue
            self.titleAttriStr.addAttribute(NSMutableAttributedString.Key.foregroundColor, value: newValue, range: NSRange(location: 0, length: self.titleAttriStr.length))
        }
        get {return self.titleLab.textColor}
    }
    public var messageColor: UIColor{
        set{
            self.messageLab.textColor = newValue
            if let attristr = self.messageAttriStr {
                attristr.addAttribute(NSMutableAttributedString.Key.foregroundColor, value: newValue, range: NSRange(location: 0, length: attristr.length))
            }
        }
        get {return self.messageLab.textColor}
    }
    public var titleFont: UIFont{
        set{
            self.titleLab.font = newValue
            self.titleAttriStr.addAttribute(NSMutableAttributedString.Key.font, value: newValue, range: NSRange(location: 0, length: self.titleAttriStr.length))
        }
        get {return self.titleLab.font}
    }
    public var messageFont: UIFont{
        set{
            self.messageLab.font = newValue
            if let attristr = self.messageAttriStr {
                attristr.addAttribute(NSMutableAttributedString.Key.font, value: newValue, range: NSRange(location: 0, length: attristr.length))
            }
        }
        get {return self.messageLab.font}
    }
    
    //自定义的视图
    var customView: UIView?
    //自定义的宽度
    //var customAlertWidth: CGFloat = 0
    
    private lazy var alertView: UIView = {
        let v = UIView.init()
        v.backgroundColor = UIColor.white
        v.layer.cornerRadius = 10
        v.layer.masksToBounds = true
        v.clipsToBounds = true
        return v
    }()
    private lazy var backTapView: UIView = {
        let v = UIView.init()
        v.backgroundColor = MZ.RGB("#141414").withAlphaComponent(0.56)
        return v
    }()
    
    
    public func addAction(_ action: MZAlertAction){
        actionList.append(action)
    }
    
    public required convenience init(title: String, message: String) {
        self.init()
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .crossDissolve
        titleAttriStr = NSMutableAttributedString.mz.initWith(text: title, font: titleLab.font, color: titleLab.textColor, alignment: .center)
        messageAttriStr = NSMutableAttributedString.mz.initWith(text: message, font: messageLab.font, color: messageLab.textColor, alignment: .center)
    }
    public required convenience init(titleAttri: NSMutableAttributedString, messageAttri: NSMutableAttributedString?) {
        self.init()
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .crossDissolve
        titleAttriStr = titleAttri
        messageAttriStr = messageAttri
    }
    public required convenience init(customview: UIView) {
        self.init()
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .crossDissolve
        self.customView = customview
    }
    
    private func addnotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(alertDismiss), name: MZAlertAction.ACTIONNotifName, object: nil)
    }
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        addnotification()
        self.title = "弹窗"
        self.view.backgroundColor = UIColor.clear
        self.view.addSubview(backTapView)
        self.view.addSubview(alertView)
        
        var maxwidth = UIScreen.main.bounds.size.width - 120
        backTapView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: self.view.frame.height)
        alertView.frame = CGRect(x: 0, y: 0, width: maxwidth, height: 30)

        var lastView: UIView?
        var alertHeight: CGFloat = 0
        if customView != nil{
            //MARK: 自定义view处理
            maxwidth = customView!.frame.size.width >= maxwidth/2 ? (customView?.frame.size.width ?? 0) : maxwidth
            alertView.addSubview(customView!)
            alertView.mz.width = maxwidth
            customView!.frame = CGRect.init(x: 0, y: 0, width: maxwidth, height: self.customView!.frame.size.height)
            alertHeight = self.customView!.frame.size.height
            lastView = self.customView!
        }else{
            //MARK: 基础标题内容处理
            var hasTitle = false
            var hasMessage = false
            var bgviewHeight:CGFloat = 0
            let bgview = UIView.init(frame: CGRect.init(x: 0, y: 0, width: maxwidth, height: 0))
            if titleAttriStr.string.count > 0 {
                hasTitle = true
            }
            if (messageAttriStr?.string.count ?? 0) > 0 {
                hasMessage = true
            }
            if hasTitle {
                bgview.addSubview(titleLab)
                titleLab.attributedText = titleAttriStr
                titleLab.frame = CGRect.init(x: 15, y: hasMessage ? 15 : 20, width: bgview.mz.width - 30, height: 0)
                titleLab.numberOfLines = 1
                let size = titleAttriStr.mz.boundingSize(maxW: titleLab.mz.width)
                titleLab.mz.height = size.height
                bgviewHeight += (hasMessage ? 15 : 20) + titleLab.mz.height
            }
            if hasMessage {
                bgview.addSubview(messageLab)
                messageLab.attributedText = messageAttriStr
                messageLab.frame = CGRect.init(x: 15, y: 20, width: bgview.mz.width - 30, height: 0)
                if hasTitle {
                    messageLab.mz.top = self.titleLab.mz.bottom + 1
                }
                messageLab.numberOfLines = 0
                let size = messageAttriStr?.mz.boundingSize(maxW: messageLab.mz.width)
                messageLab.mz.height = size?.height ?? 0
                bgviewHeight += CGFloat((hasTitle ? 1 : 20)) + messageLab.mz.height
            }
            alertView.addSubview(bgview)
            bgview.mz.height = ceil(bgviewHeight) + 10
            lastView = bgview
            alertHeight += bgview.mz.height
        }
        
        //MARK: 按钮处理
        let actionHeight:CGFloat = 44
        if self.actionList.count == 0 {
            let cancel = MZAlertAction.init(title:"取消") { action in
                
            }
            self.addAction(cancel)
        }
        
        if self.actionList.count == 1 {
            let action = self.actionList.first
            alertView.addSubview(action!)
            action?.frame = CGRect.init(x: 0, y: lastView != nil ? lastView!.mz.bottom : 10, width: maxwidth, height: actionHeight)
            if action?.titleColor == nil {
                action?.titleColor = .systemBlue
            }
            alertHeight += actionHeight
            if lastView != nil {
                let line1 = UIView.init();line1.backgroundColor = MZ.RGB("#F5F5F5")
                alertView.addSubview(line1)
                line1.frame = CGRect.init(x: 0, y: action!.mz.top, width: maxwidth, height: 0.5)
            }
        }else if self.actionList.count == 2{
            
            let action1 = self.actionList.first
            let action2 = self.actionList.last
            
            alertView.addSubview(action1!)
            alertView.addSubview(action2!)
            action1?.frame = CGRect.init(x: 0, y: lastView != nil ? lastView!.mz.bottom : 10, width: maxwidth/2, height: actionHeight)
            if action1?.titleColor == nil {
                action1?.titleColor = .systemBlue
            }
            action2?.frame = CGRect.init(x: action1!.mz.right, y: action1!.mz.top, width: maxwidth/2, height: actionHeight)
            if action2?.titleColor == nil {
                action2?.titleColor = .systemBlue
            }
            alertHeight += actionHeight
            if lastView != nil {
                let line1 = UIView.init();line1.backgroundColor = MZ.RGB("#F5F5F5")
                let line2 = UIView.init();line2.backgroundColor = MZ.RGB("#F5F5F5")
                alertView.addSubview(line1)
                alertView.addSubview(line2)
                line1.frame = CGRect.init(x: 0, y: action1!.mz.top, width: maxwidth, height: 0.5)
                line2.frame = CGRect.init(x: action1!.mz.right, y: action1!.mz.top, width: 0.5, height: actionHeight)
            }
        }else{
            
        }
        //MARK: 弹出
        alertView.layoutIfNeeded()
        alertView.mz.height = alertHeight
        alertShow()
    }
    
    private func alertShow(){
        self.backTapView.alpha = 0
        self.alertView.alpha = 0
        self.alertView.transform = CGAffineTransformMakeScale(1.1, 1.1)
        self.alertView.center = CGPoint.init(x: self.view.mz.width/2, y: self.view.mz.height/2)
        UIView.animate(withDuration: 0.2) {
            self.backTapView.alpha = 1
            self.alertView.alpha = 1
        }completion: { finished in
            UIView.animate(withDuration: 0.2) {
                self.alertView.transform = CGAffineTransformMakeScale(1, 1)
                self.view.layoutIfNeeded()
            }
        }
    }
    @objc private func alertDismiss(){
        self.customView = nil
        self.view.endEditing(true)
        self.dismiss(animated: true)
    }
}

